<template>
  <!-- 初始库存入库 -->
  <view class="content">
    <blueTeethBtn></blueTeethBtn>
    <view class="info-views">
      <view
        class="line-view"
        style="align-items: center">
        <view class="line-text">工厂</view>
        <view
          class="line-value mini-text"
          @click="factorySelectShow = true"
          :style="{ 'pointer-events': showPrint ? 'none' : 'auto' }">
          {{ factoryName || '点击选择工厂' }}
        </view>
      </view>

      <u-select
        v-model="factorySelectShow"
        mode="single-column"
        :list="factorySelectList"
        @confirm="factorySelectConfirm"></u-select>

      <view
        class="line-view"
        style="align-items: center">
        <view class="line-text">仓位</view>
        <view class="line-value">
          <uni-easyinput
            v-model="scanList[1].val"
            border
            placeholder="请扫描仓位"
            :focus="stockFocus"
            @confirm="stockScan"
            :disabled="showPrint"
            @focus="scanList[1].val = ''"></uni-easyinput>
        </view>
      </view>

      <view
        class="line-view"
        style="align-items: center; margin: 10rpx 0"
        v-if="!showPrint">
        <view class="line-text">物料</view>
        <view
          class="line-value mini-text"
          @click="doPopShow">
          点击选择物料
        </view>
      </view>

      <view
        class="line-view"
        style="
          align-items: flex-start;
          justify-content: space-between;
          font-size: 30rpx;
          color: #b8b8b8;
          font-weight: 700;
        "
        v-if="stockInfo.id">
        <view style="width: 450rpx">
          {{ stockInfo.name }}
        </view>
        <view style="width: 200rpx">
          数据条目：{{ projectInfo.length || 0 }}
        </view>
      </view>
    </view>

    <!-- 已添加BOM -->
    <view
      class="info-views"
      style="padding: 10rpx"
      v-if="projectInfo.length > 0">
      <view
        class="line-view project-line-view"
        v-for="(item, index) of projectInfo"
        :class="{ printCheck: item.printCheck }"
        :key="index"
        @click="printCheckItems(index)">
        <view
          class="project-views"
          style="font-size: 38rpx">
          <text style="font-weight: 700">{{ item.name }}</text>
          <view
            class="titel-btn-view"
            v-if="!showPrint"
            @click.stop="delInfo(index)">
            <uni-icons
              type="trash"
              size="28"></uni-icons>
          </view>
          <view
            class="titel-btn-view"
            v-else>
            <uni-icons
              v-if="item.printCheck == 1"
              color="#3067E8"
              type="checkbox-filled"
              size="22" />
            <uni-icons
              v-else
              color="#484848"
              type="circle"
              size="22" />
          </view>
        </view>

        <view class="project-views">
          <view class="title-view">物料代码</view>
          {{ item.code }}
        </view>

        <view
          class="project-views"
          style="align-items: flex-start">
          <view class="title-view">规格型号</view>
          {{ item.productModel }}
        </view>

        <view class="project-views">
          <view class="title-view">批号</view>
          <uni-easyinput
            v-model="item.batch"
            border
            placeholder="请输入批号"
            :disabled="showPrint" />
        </view>

        <view class="project-uni-datetime-picker">
          <view class="title-view">入库日期</view>
          <uni-datetime-picker
            style="display: inline !important"
            type="date"
            :clear-icon="false"
            v-model="item.receiptDate"
            :disabled="showPrint" />
        </view>

        <view class="project-views">
          <view style="width: 48%; align-items: center">
            <view class="title-view">数量</view>
            <view class="title-val">
              <uni-easyinput
                v-model="item.quality"
                border
                placeholder="请输入数量"
                type="number"
                :disabled="showPrint" />
            </view>
          </view>

          <view style="margin-left: auto">
            <view class="title-view">单位</view>
            <view class="title-val">
              {{ item.unitName || '--' }}
            </view>
          </view>
        </view>

        <view class="project-views">
          <view style="width: 48%">
            <view class="title-view">辅助数量</view>
            <view class="title-val">
              <!-- {{ item.quality || '--' }} -->
              --
            </view>
          </view>

          <view style="margin-left: auto">
            <view class="title-view">辅助单位</view>
            <view class="title-val">
              <!-- {{ item.unitName || '--' }} -->
              --
            </view>
          </view>
        </view>
      </view>
    </view>

    <view class="btn-style">
      <view
        class="submit-button"
        v-if="projectInfo.length > 0 && !showPrint"
        @click="$u.throttle(submit, 1000)">
        提 交
      </view>
    </view>

    <view
      class="btn-bottom"
      v-if="showPrint">
      <view
        class="submit-button reset"
        @click="resetPage">
        重置
      </view>
      <view
        class="submit-button"
        @click="doPrint"
        v-if="printLength > 0">
        打印
      </view>
    </view>

    <!-- 选择物料弹出层 -->
    <u-popup
      v-model="popShow"
      mode="center"
      closeable>
      <view class="pop-view">
        <view class="pop-search">
          <view
            class="line-view"
            style="justify-content: space-between">
            <view class="line-halfway">
              <uni-easyinput
                v-model="search.code"
                border
                placeholder="物料代码"
                :placeholderStyle="placeholderStyle"></uni-easyinput>
            </view>
            <view class="line-halfway">
              <uni-easyinput
                v-model="search.name"
                border
                placeholder="物料名称"
                :placeholderStyle="placeholderStyle"></uni-easyinput>
            </view>
          </view>

          <view
            class="line-view"
            style="align-items: center; padding: 0">
            <view class="line-halfway">
              <uni-easyinput
                v-model="search.productModel"
                border
                placeholder="规格型号"
                :placeholderStyle="placeholderStyle"></uni-easyinput>
              <!-- <uni-data-select
                v-model="search.createType"
                :localdata="range"
                placeholder="选择物料属性"></uni-data-select> -->
            </view>
            <view
              class="line-search"
              @click="doSearch">
              <uni-icons
                type="search"
                color="#a7a7a7"
                size="18"
                style="margin-bottom: -5rpx; margin-right: 5rpx"></uni-icons>
              搜索
            </view>
          </view>
        </view>

        <view class="pop-info">
          <scroll-view
            style="height: 100%"
            :scroll-top="scrollTop"
            scroll-y="true"
            class="scroll-Y">
            <view
              class="pop-card"
              :class="{ isCheck: item.check == 1 }"
              v-for="(item, index) of tableData"
              :key="index"
              @click="addInfo(index)">
              <view class="popCard-name">
                <view class="pop-title">
                  {{ item.name }}
                </view>
                <view class="pop-check">
                  <uni-icons
                    v-if="item.check == 1"
                    color="#3067E8"
                    type="checkbox-filled"
                    size="22" />
                  <uni-icons
                    v-else
                    color="#484848"
                    type="circle"
                    size="22" />
                </view>
              </view>
              <view class="popCard-line">
                <view class="popCard-li-label">物料编码</view>
                <view class="popCard-li-value">
                  {{ item.code }}
                </view>
              </view>
              <view class="popCard-line">
                <view class="popCard-li-label">规格型号</view>
                <view class="popCard-li-value">
                  {{ item.productModel }}
                </view>
              </view>
              <view class="popCard-line">
                <view class="popCard-li-label">计量单位</view>
                <view class="popCard-li-value">
                  {{ item.unitName }}
                </view>
              </view>
              <!-- 	<view class="popCard-line">
								<view class="popCard-half">
									<view class="popCard-li-label">批号</view>
									<view class="popCard-li-valueLittle">
										{{ item.batch||'--' }}
									</view>
								</view>
							</view> -->
              <!-- 								<view class="popCard-half">
									<view class="popCard-li-label">已收回数</view>
									<view class="popCard-li-valueLittle">
										{{ item.receiveQuantity || 0 }}
									</view>
								</view>
							</view>
							<view class="popCard-line">
								<view class="popCard-li-label">图号</view>
								<view class="popCard-li-value">
									{{ item.materialCode }}
								</view>
							</view> -->
            </view>
          </scroll-view>
        </view>

        <view class="pop-bottom">
          <uni-pagination
            :current="search.page"
            :total="search.total"
            :pageSize="search.size"
            @change="pageChange" />
        </view>
      </view>

      <u-select
        v-model="providerSelectShow"
        mode="single-column"
        :list="providerSelectList"
        @confirm="providerSelectConfirm"></u-select>
    </u-popup>
    <u-back-top :scroll-top="scrollTop"></u-back-top>
  </view>
</template>

<script>
var that;
import * as bter from '@/components/printCom/bter.js';
import * as zksdk from '@/components/printCom/bluetoolth.js';
import blueTeethBtn from '@/components/blueTeethBtn/blueTeethBtn.vue';
export default {
  components: {
    blueTeethBtn,
  },
  data() {
    return {
      headerList: {
        Authorization: uni.getStorageSync('token'),
        LoginEntryType: 'mobile',
      },
      printLength: 0,
      printIdList: [],
      showPrint: false, //展示打印按钮
      tableData: [], //查询零件
      range: [
        {
          value: '1',
          text: '外购',
        },
        {
          value: '2',
          text: '自制',
        },
        {
          value: '3',
          text: '委外',
        },
      ],
      search: {
        code: null,
        name: null,
        total: 0,
        page: 1,
        size: 20,
        productModel: null,
      },
      providerName: null, //供应商
      providerSelectShow: false, //供应商
      providerSelectList: [], //供应商
      quantity: null,
      boxFocus: true,
      stockFocus: false,
      popShow: false, //选择零件弹窗
      popFocus: false,
      boxInfo: {}, //扫描框的信息
      projectInfo: [], //添加的数组
      projectNumber: null, //项目号
      projectId: null, //项目ID
      serialNumber: null,
      factoryId: null,
      factoryName: null, //工厂名称
      factorySelectShow: false, //显示选择工厂下拉框
      projectSelectList: [], //选择项目数组
      factorySelectList: [], //选择工厂数组
      baseUrl: global.reqHeard,
      action: '',
      stockInfo: {},
      productFocus: true,
      scanList: [
        {
          val: null,
        },
        {
          val: null,
        },
        {
          val: null,
        },
      ],
      placeholderStyle: 'font-size:25rpx;color:#6A6A6A',
      scrollTop: 0,
      infoList: [],
    };
  },
  onPageScroll(e) {
    this.scrollTop = e.scrollTop;
  },
  onLoad() {
    that = this;
    that.action = `${global.reqHeard}/api/baseFiles/upload`;
    that.getList();
  },
  onBackPress() {
    if (this.popShow) {
      this.popShow = false;
      return true;
    }
  },
  methods: {
    // 发送二进制数据
    writeBLECharacteristicValue(obj) {
      // obj = {
      //   stackCode: '202310080002', //堆码
      //   projectNumber: 'YD230928', //项目号
      //   materialCode: 'SEW007812112', // 图号
      //   materialName: '立柱焊接T909L.2.11.2', //物料名称
      // };
      let deviceId = getApp().globalData.deviceId;
      if (!deviceId) {
        uni.showToast({
          icon: 'none',
          title: '缺少设备Id,请去蓝牙页面设置',
        });
        return;
      }
      let strCmd = zksdk.CreatCPCLPage(576, 400, 1, 0);
      strCmd += zksdk.addCPCLQRCode(340, 20, 'Q', 2, 7, obj.barcode);
      strCmd += zksdk.addCPCLText(80, 20, '7', '2', 0, obj.barcode);
      strCmd += zksdk.addCPCLText(10, 80, '7', '2', 0, '编号:');
      strCmd += zksdk.addCPCLText(100, 80, '7', '2', 0, obj.productCode);
      strCmd += zksdk.addCPCLText(10, 150, '7', '2', 0, '单位:');
      strCmd += zksdk.addCPCLText(100, 150, '7', '2', 0, obj.unitName);
      strCmd += zksdk.addCPCLText(10, 220, '7', '2', 0, '名称:');
      strCmd += zksdk.addCPCLText(100, 220, '7', '2', 0, obj.productName);
      strCmd += zksdk.addCPCLText(10, 290, '7', '2', 0, '规格:');
      strCmd += zksdk.addCPCLText(100, 290, '7', '2', 0, obj.productModel);
      strCmd += zksdk.addCPCLGAP();
      strCmd += zksdk.addCPCLPrint();
      bter.BTER.printSomething(strCmd);
    },
    fnishPick() {
      uni.showModal({
        title: '提示',
        content: '是否结束拣货？',
        success: function (res) {
          if (res.confirm) {
            uni.showLoading({
              mask: true,
              title: '请求中...',
            });
            that.infoList = [];
            that.$u
              .post('/api/outsourceWhiteReceiveDetail/finishPick', {
                id: that.boxInfo.id,
              })
              .then((res) => {
                if (res.code != 0) {
                  this.$u.toast(res.message);
                  return;
                }
                uni.showToast({
                  mask: true,
                  icon: 'none',
                  title: '提交成功',
                });
                setTimeout(function () {
                  uni.redirectTo({
                    url: '/pages/yundingOut/white/whiteTally',
                  });
                }, 1000);
              });
          }
        },
      });
    },
    doPrint() {
      // that.boxInfo.id
      const list = that.$u.deepClone(that.projectInfo);
      let printList = [];
      for (const item of list) {
        if (item.printCheck) {
          printList.push(item);
        }
      }
      for (let one of printList) {
        this.writeBLECharacteristicValue(one);
      }
      // const baseUrl = uni.getStorageSync('printUrl');
      // uni.request({
      //   url: 'http://' + baseUrl,
      //   data: res.data,
      //   method: 'POST',
      //   success: (req) => {
      //     this.$u.toast('请求成功');
      //   },
      //   fail: (err) => {},
      // });
      // });
    },
    printCheckItems(e) {
      if (that.showPrint) {
        const list = that.$u.deepClone(that.projectInfo);
        list[e].printCheck = !list[e].printCheck;
        that.printLength = 0;
        for (const item of list) {
          if (item.printCheck) {
            that.printLength = 1;
          }
        }
        that.projectInfo = that.$u.deepClone(list);
      }
    },
    resetPage() {
      uni.showModal({
        title: '提示',
        content: '重置会清空页面信息，是否继续？',
        success: function (res) {
          if (res.confirm) {
            uni.redirectTo({
              url: 'lnitialInventory',
            });
          }
        },
      });
    },
    doSearch() {
      uni.showLoading({
        mask: true,
        title: '查询中...',
      });
      //分页-1 看一下search原数据
      const search = that.$u.deepClone(that.search);
      search.factoryId = that.factoryId;
      search.page = search.page - 1;
      that.$u.get('/api/product', search).then((res) => {
        if (res.code != 0) {
          uni.hideLoading();
          this.$u.toast(res.message);
          return false;
        }
        const list = res.data.content;
        for (const item of res.data.content) {
          item.check = 0;
        }

        // 搜索后 如果存在已选中数组 对比添加选中状态
        if (that.projectInfo.length > 0) {
          for (const infoItem of that.projectInfo) {
            for (const listItem of list) {
              if (infoItem.id === listItem.id) {
                listItem.check = 1;
                break;
              }
            }
          }
        }

        that.tableData = list;
        that.search.total = Number(res.data.totalElements);
        if (!that.popShow) {
          that.popShow = true;
        }
      });
    },
    addInfo(e) {
      if (that.projectInfo.length == 20) {
        that.$u.toast('最多添加20件');
        return false;
      }
      const list = that.$u.deepClone(that.tableData);
      for (const item of that.projectInfo) {
        if (list[e].id == item.id) {
          that.$u.toast('该物料已添加');
          return false;
        }
      }
      list[e].check = 1;
      that.tableData = that.$u.deepClone(list);
      const now = new Date();
      const year = now.getFullYear();
      const month = now.getMonth() + 1;
      const date = now.getDate();
      let receiptDate = year + '-' + month + '-' + date;
      list[e].receiptDate = receiptDate;
      list[e].stockPositionId = that.stockInfo.id;
      list[e].stockId = that.stockInfo.stockId;
      list[e].stockAreaId = that.stockInfo.stockAreaId;
      list[e].productId = list[e].id;
      list[e].productCode = list[e].code;
      that.projectInfo.push(list[e]);
    },
    doPopShow() {
      if (!that.stockInfo.id) {
        this.$u.toast('请先扫描仓位');
        return false;
      } else {
        that.doSearch();
      }
    },
    pageChange(e) {
      const { type, current } = e;
      that.search.page = current;
      that.doSearch();
    },
    // 提交
    submit() {
      if (!that.stockInfo.id) {
        this.$u.toast('请扫描框码');
        return false;
      }

      uni.showModal({
        title: '提示',
        content: '是否确认提交？',
        success: function (res) {
          if (res.confirm) {
            uni.showLoading({
              mask: true,
              title: '请稍后...',
            });
            const param = [];
            for (const item of that.projectInfo) {
              if (
                item.quality == undefined ||
                !item.quality ||
                item.quality == 0
              ) {
                that.$u.toast('请输入数量');
                return false;
              }

              // if (!item.batch) {
              //   that.$u.toast('请输入批号');
              //   return false;
              // }
              // const receiveQuantity = item.receiveQuantity || 0; // 如果receiveQuantity为空，则将其视为0
              // const quantity = item.quantity - receiveQuantity;

              // if (item.currentQuantity > quantity) {
              // 	that.$u.toast(item.materialName + '理货数量不能大于可用数量');
              // 	return false;
              // }

              param.push(item);
            }
            console.log(param, 'outsourceWhiteReceiveDetailList');
            that.$u
              .post('/api/initInventoryInMain', {
                inventoryInDetails: param,
                factoryId: that.factoryId,
              })
              .then((res) => {
                console.log(res);
                if (res.code != 0) {
                  uni.hideLoading();
                  this.$u.toast(res.message);
                  return false;
                }
                uni.hideLoading();
                uni.showToast({
                  mask: true,
                  icon: 'none',
                  title: '提交成功',
                });
                that.projectInfo = res.data;
                // that.printIdList = [];
                // for (const item of res.data) {
                // 	that.printIdList.push(item.id);
                // }
                that.showPrint = true;
              })
              .catch((err) => {
                uni.hideLoading();
              });
          }
        },
      });
    },

    providerSelectConfirm(e) {
      that.search.providerName = e[0].label;
      that.search.suplierId = e[0].value;
    },
    delInfo(e) {
      const list = this.$u.deepClone(this.projectInfo);
      const tableData = this.$u.deepClone(this.tableData);
      const id = list[e].id;
      list.splice(e, 1);
      this.projectInfo = this.$u.deepClone(list);
      for (const item of tableData) {
        if (item.id == id) {
          item.check = 0;
        }
      }
      that.tableData = this.$u.deepClone(tableData);
    },
    getList() {
      that.$u.post('/api/outsourceProject/getFactoryByUser', {}).then((res) => {
        that.factorySelectList = [];
        for (const item of res.data) {
          const loop = {
            value: item.id,
            label: item.name,
          };
          that.factorySelectList.push(loop);
        }
        that.factorySelectConfirm([that.factorySelectList[0]]);
      });
    },
    // 选择项目下拉框确认
    projectSelectConfirm(e) {
      that.projectNumber = e[0].value;
    },
    setFocus() {
      that.stockFocus = false;
      setTimeout(function () {
        that.$nextTick(function () {
          that.stockFocus = true;
        });
      }, 100);
    },
    // 选择工厂确认
    factorySelectConfirm(e) {
      that.projectInfo = [];
      that.factoryId = e[0].value;
      that.factoryName = e[0].label;
      that.stockInfo = {};
      that.setFocus();
    },
    stockScan(e) {
      if (!that.factoryId) {
        this.$refs.uToast.show({
          title: '请选择工厂',
          type: 'error',
        });
        return;
      }
      this.$u
        .get('/wms/mobile/api/getStockPalace', {
          code: e,
          factoryId: that.factoryId,
        })
        .then((res) => {
          that.stockInfo = res.data;
          that.projectInfo = [];
          that.doSearch();
        })
        .catch((err) => {
          that.setFocus();
        });
    },
  },
};
</script>

<style lang="scss">
page {
  background-color: #f8f8f8;
  padding-bottom: 150rpx;
}

.content {
  height: 100%;
}

.pop-view {
  height: 100vh;
  width: 750rpx;
  padding: 45rpx 10rpx 5rpx 10rpx;
  // display: flex;
  font-size: 35rpx;
  flex-direction: column;
  box-sizing: border-box;

  .pop-search {
    padding: 15rpx;
  }

  .pop-info {
    flex: 1;
    overflow: hidden;
    padding: 0 15rpx 15rpx 15rpx;
    background-color: #f8f8f8;

    .pop-card {
      padding: 25rpx;
      background-color: #fff;
      margin: 15rpx 0;
      border-radius: 15rpx;
      font-size: 30rpx;
      border: 1rpx solid #fff;

      view {
        margin: 2rpx 0;
      }

      .popCard-name {
        color: #000;
        font-size: 35rpx;
        margin-bottom: 10rpx;
        display: flex;

        .pop-title {
          width: 700rpx;
        }
      }

      .popCard-line {
        display: flex;
        align-items: center;

        .popCard-li-label {
          width: 160rpx;
          color: #999;
        }

        .popCard-half {
          display: flex;
        }

        .popCard-li-value {
          width: 500rpx;
          color: #555;
        }

        .popCard-li-valueLittle {
          width: 210rpx;
          color: #555;
        }
      }
    }

    .isCheck {
      border: 1rpx solid #9ca6ff;
    }
  }

  .pop-bottom {
    height: 80rpx;
    padding: 10rpx 25rpx 0 25rpx;
  }
}

.info-views {
  background-color: #fff;
  padding: 15rpx 20rpx;
  padding-bottom: 10rpx;
  margin-bottom: 25rpx;
}

.mini-text {
  font-size: 30rpx;
}

.sub-text {
  margin-left: 10rpx;
  color: #3067e8;
  text-decoration: underline;
}

.project-views {
  width: 720rpx;
  padding-left: 10rpx;
  display: flex;
  align-items: center;
  margin-bottom: 10rpx;

  view {
    display: flex;
  }
}

.project-uni-datetime-picker {
  width: 720rpx;
  padding-left: 10rpx;
  display: flex;
  align-items: center;
  margin-bottom: 10rpx;
}

.project-line-view {
  flex-direction: column;
  margin-top: 25rpx;
  border-radius: 20rpx;
  border: 1rpx solid #fff;
}

// .project-line-view:last-of-type {
// 	border: none;
// }

.printCheck {
  border: 1rpx solid #3067e8;
}

.title-view {
  width: 150rpx;
  color: #909399;
}

.title-val {
  width: 170rpx;
  color: #303133;
}

.btn-style {
  display: flex;
  justify-content: center;
}

.submit-button {
  background-color: #3067e8;
  color: #fff;
  display: flex;
  align-items: center;
  justify-content: center;
  margin: 30rpx auto;
  width: 46%;
  border-radius: 15rpx;
  height: 80rpx;
  font-size: 36rpx;
}

.over {
  background-color: #f8f8f8;
  color: #3067e8;
  border: 1rpx solid #3067e8;
}

.pop-button {
  width: 290rpx;
  background-color: #3067e8;
  color: #fff;
  display: flex;
  align-items: center;
  justify-content: center;
  margin: 10rpx auto;
  border-radius: 15rpx;
  height: 75rpx;
  font-size: 35rpx;
}

.line-view {
  width: 100%;
  display: flex;
  align-items: flex-start;
  padding: 15rpx 0;

  .line-halfway {
    width: 345rpx;
  }

  .line-search {
    display: flex;
    align-items: center;
    padding-left: 25rpx;
    color: #a7a7a7;
    font-size: 32rpx;
  }

  .line-text {
    width: 150rpx;
    font-weight: 700;
    color: #555;
  }

  .line-value {
    width: 550rpx;
    display: flex;
    color: #6a6a6a;
  }
}

.btn-bottom {
  position: fixed;
  bottom: 0;
  left: 0;
  width: 750rpx;
  background-color: #fff;
  z-index: 9;
  display: flex;

  .submit-button {
    width: 325rpx;
    margin: 15rpx auto 25rpx auto;
  }

  .reset {
    color: #3067e8;
    background-color: #fff;
    border: 1rpx solid #3067e8;
  }
}

.titel-btn-view {
  margin-left: auto;
  display: flex;
  align-items: center;
}


</style>
